# import jusmargui
from PySide2.QtWidgets import (
    QVBoxLayout,
    QHBoxLayout,
    QPushButton,
    QFileDialog,
)
from PySide2.QtCore import Qt, Signal

# from PySide2.QtGui import QPixmap, QDoubleValidator, QIntValidator, QImage
import sys
import csv
import os
from gui.controls import envs
from .. import message_box as MBox
from .. import config as Config
from ..utils import Utils

from ..dlg_model_params import DlgModelMutliParams
from .mateial_table import MaterialTable


class DlgMaterialLibrary(DlgModelMutliParams):
    materialLibrary_save_signal = Signal(object)

    def __init__(self, parent=None, data=[]):
        super().__init__(parent)
        self.setWindowTitle("材料库")
        self.resize(600, 600)

        layout = QVBoxLayout()
        self.table = MaterialTable(rows=0, columns=6)
        self.table.verticalHeader().setVisible(True)
        self.table.setHorizontalHeaderLabels(
            ["id", "名称", "密度", "弹性模量", "泊松比", "剪切模量"]
        )
        self.table.noEditHint = "材料已被使用，不可修改名称！"
        self.table.rowSetInt([0])
        self.table.rowSetFloat([2, 3, 4, 5])
        if Config.useLibraryLocking:
            self.table.isHandleDel = True
        self.table.uniqueFlagColumn = 1

        layout.addWidget(self.table)

        btnLayout = QHBoxLayout()
        addBtn = QPushButton("新增")
        importBtn = QPushButton("导入csv")
        exportBtn = QPushButton("导出csv")
        clearBtn = QPushButton("清空")
        cancelBtn = QPushButton("取消")
        okBtn = QPushButton("确定")

        btnLayout.setAlignment(Qt.AlignCenter)
        btnLayout.addWidget(addBtn)
        btnLayout.addWidget(importBtn)
        btnLayout.addWidget(exportBtn)
        btnLayout.addWidget(clearBtn)
        btnLayout.addWidget(okBtn)
        btnLayout.addWidget(cancelBtn)
        layout.addLayout(btnLayout)

        addBtn.clicked.connect(self.on_addBtn_clicked)
        importBtn.clicked.connect(self.on_importBtn_clicked)
        exportBtn.clicked.connect(self.on_exportBtn_clicked)
        clearBtn.clicked.connect(self.on_clearBtn_clicked)
        okBtn.clicked.connect(self.on_okBtn_clicked)
        cancelBtn.clicked.connect(self.close)

        self.setLayout(layout)

        self.cacheFile = Config.cachePath + "materialLibrary.json"
        self.loadTableData(self.cacheFile, self.table)
        # Utils.handleTableNoEdit(data=data.get("main")or[],table=self.table)
        if Config.useLibraryLocking:
            self.lockingData = self.handleLockingTable()
            envs.ipimas_changeLockMaterial = (
                lambda *args, **kwargs: self.lockLibraryChange(*args, **kwargs)
            )

    def lockLibraryChange(self):
        if self.isVisible():
            self.lockingData = self.handleLockingTable()

    def handleLockingTable(self):
        lockingData = Utils.read_json(Config.materialTable)
        for row in range(self.table.rowCount()):
            item = self.table.item(row, 0)
            if item and item.text() in lockingData:
                item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                item.setReadyOnly(True)
                self.table.hasNoEditCell = True
        return lockingData

    def on_addBtn_clicked(self):
        self.table.addRow(isAddIncrementing=True)

    def on_importBtn_clicked(self):
        filePath = Utils.ImportFile()
        if filePath:
            _, fileExtension = os.path.splitext(filePath)
            fileExtension = fileExtension.lower()
            if fileExtension == ".json":
                self.loadTableList(filePath, self.table)
            elif fileExtension == ".csv":
                self.load_csv(filePath)
                
    def on_exportBtn_clicked(self):
        Utils.export_to_csv(self.table)

    def on_okBtn_clicked(self):
        data = self.table.getTableDictFirstNoNull()
        if isinstance(data, int):
            # MBox.warning(f"第{data}行名称不可为空!")
            return
        # data = self.table.validate_table_data()
        if data == False:
            # MBox.warning("表格中存在未填写的内容，请填写完整数据后再保存!")
            return
        if isinstance(data, str):
            # MBox.warning(f"第{data}行名称已存在!")
            return
        # data = Utils.sortDictCustom(data)
        Utils.write_json(self.cacheFile, data)
        if Config.useLibraryLocking:
            self.updateLockingTable(data)
        self.close()
        self.materialLibrary_save_signal.emit(data)
        if hasattr(envs, "ipimas_changeMaterial"):
            envs.ipimas_changeMaterial(library=data)

    def updateLockingTable(self, data):
        for key, item in self.lockingData.items():
            if key in data:
                item["content"] = data[key]
        Utils.write_json(Config.materialTable, self.lockingData)

    def on_clearBtn_clicked(self):
        self.table.clearRow()

    def load_csv(self, filename):
        # data = Utils.loadCsvUniquId(filename, labList=["id","名称","密度","弹性模量","泊松比","剪切模量"], uniqueLabs=["名称"])
        data = Utils.loadCsv(
            filename, labList=["id", "名称", "密度", "弹性模量", "泊松比", "剪切模量"]
        )
        if data:
            copyCsvData = data.copy()
            [nameDict, idDict] = self.table.getTableDictList()
            for addIndex in range(len(copyCsvData) - 1, -1, -1):  # 倒序遍历
                csvRow = copyCsvData[addIndex]
                # 更新同名
                if (
                    csvRow[1] is not None
                    and csvRow[1] != ""
                    and str(csvRow[1]) in nameDict
                ):
                    self.table.updateRowData(nameDict[str(csvRow[1])]["row"], csvRow)
                    del data[addIndex]
                    continue
                # 更新同id
                if (
                    csvRow[0] is not None
                    and csvRow[0] != ""
                    and str(csvRow[0]) in idDict
                ):
                    self.table.updateRowData(idDict[str(csvRow[0])]["row"], csvRow)
                    del data[addIndex]
            self.table.addMulitRows(data)

    def loadTableData(self, file, table):
        data = Utils.read_json(file)
        for _, row_data in data.items():
            table.addRow(rowData=row_data)

    def loadTableList(self, file, table):
        data = Utils.read_json(file)
        for row_data in data:
            table.addRow(rowData=row_data)


# if __name__ == "__main__":
#     app = QApplication(sys.argv)
#     window = MaterialLibraryDialog()
#     window.show()
#     sys.exit(app.exec_())
